import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { queryDept, createDept, updateDept, deleteDept } from "../server";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { isAllEmpty } from "@pureadmin/utils";

export function useDept() {
  const form = reactive({
    name: "",
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
    pages: 0,
  });

  const columns: TableColumnList = [
    {
      label: "部门ID",
      prop: "id",
      // width: 100
    },
    {
      label: "部门名称",
      prop: "name",
      // width: 200,
      align: "left",
    },

    {
      label: "操作",
      fixed: "right",
      // width: 210,
      slot: "operation",
    },
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        name: form.name || undefined,
        page: pagination.page,
        per_page: pagination.per_page,
      };

      const data = await queryDept(params);

      if (data.code === 2000) {
        dataList.value = data.data || [];
        if (data.pagination) {
          pagination.page = data.pagination.page;
          pagination.per_page = data.pagination.per_page;
          pagination.total = data.pagination.total;
          pagination.pages = data.pagination.pages;
        }
      } else {
        message(data.message || "查询失败", { type: "error" });
        dataList.value = [];
      }
    } catch (error) {
      console.error("查询部门失败:", error);
      message("查询部门失败", { type: "error" });
      dataList.value = [];
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.per_page = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.page = val;
    onSearch();
  }

  function openDialog(title = "新增", row?: any) {
    addDialog({
      title: `${title}部门`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          name: row?.name ?? "",
        },
      },
      width: "400px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as any;

        async function chores() {
          try {
            let result;
            if (title === "新增") {
              result = await createDept({ name: curData.name });
            } else {
              result = await updateDept({
                department_id: curData.id,
                name: curData.name,
              });
            }

            if (result.code === 2000) {
              message(`${title}部门成功`, { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            } else {
              message(result.message || `${title}部门失败`, { type: "error" });
            }
          } catch (error) {
            console.error(`${title}部门失败:`, error);
            message(`${title}部门失败`, { type: "error" });
          }
        }

        FormRef.validate((valid) => {
          if (valid) {
            chores();
          }
        });
      },
    });
  }

  async function handleDelete(row) {
    try {
      const result = await deleteDept({ department_id: row.id });
      if (result.code === 2000) {
        message(`删除部门 ${row.name} 成功`, { type: "success" });
        onSearch();
      } else {
        message(result.message || "删除部门失败", { type: "error" });
      }
    } catch (error) {
      console.error("删除部门失败:", error);
      message("删除部门失败", { type: "error" });
    }
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    /** 分页大小改变 */
    handleSizeChange,
    /** 当前页改变 */
    handleCurrentChange,
    handleSelectionChange,
  };
}
